package com.zyx.concurrentdemo.mytest.c08;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/19 13:46
 * desc: Executors案例
 */
@Slf4j(topic = "c.ExecutorsDemo")
public class ExecutorsDemo {

    public static void main(String[] args) {
        test2();
    }

    public static void test2() {
        // 返回的实际是 FinalizableDelegatedExecutorService 对象, 为 AbstractExecutorService 实现
        // 无法通过强转获取 ThreadPoolExecutor 对象从而修改线程池参数
        ExecutorService pool = Executors.newSingleThreadExecutor(new ThreadFactory() {
            private final AtomicInteger number = new AtomicInteger();

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "t-" + number.getAndIncrement());
            }
        });

        for (int i = 0; i < 3; i++) {
            int j = i;
            pool.submit(() -> {
                log.debug("runner {}" , j);
                int k = 1 / 0;
            });
        }
    }

    public static void test1() {
        // 返回的实际是 ThreadPoolExecutor 对象, 可以通过强转获得
        // 从而修改线程池参数
        ExecutorService pool = Executors.newFixedThreadPool(2, new ThreadFactory() {
            private final AtomicInteger number = new AtomicInteger();
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "t-" + number.getAndIncrement());
            }
        });

        for (int i = 0; i < 3; i++) {
            int j = i;
            pool.submit(() -> {
                log.debug("runner {}" , j);
                int k = 1 / 0;
            });
        }
    }

}
